//
//  PersionInfoViewController.m
//  PeopleStreet
//
//  Created by 喻飞 on 16/1/29.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "PersionInfoViewController.h"
#import "PhotoSheetView.h"
#import "UICustomActionSheet.h"
#import "STActionSheet.h"
#import "DZNPhotoEditorViewController.h"
#import "UIImagePickerController+Edit.h"
#import "UIImageView+WebCache.h"
#import <UIImageView+RJLoader.h>
#import "ScroButton.h"
#import "OneLevelPickerView.h"
#import "ThreeLevelPickerView.h"
#import "DbDao.h"
#import "CityArea.h"
#import "PhotoPopView.h"
@interface PersionInfoViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)ScroButton * boyButton;
@property (strong, nonatomic) IBOutlet UITextField *personNameField;
@property (strong, nonatomic) IBOutlet UILabel *homePlaceLabel;
@property (strong, nonatomic) IBOutlet UIView *knowledgeView;
@property (strong, nonatomic) IBOutlet UILabel *knowledgeLabel;
@property (strong, nonatomic) IBOutlet UILabel *brithdayLabel;
@property (strong, nonatomic) IBOutlet UIButton *maskView;
@property (strong, nonatomic) IBOutlet UIView *changeAddressVIew;
@property (strong, nonatomic) IBOutlet UITableView *tableView;

@property(nonatomic,strong)NSMutableArray * captionArray;
@property(nonatomic,strong)NSMutableArray * cityArray;
@property(nonatomic,strong)NSMutableArray * sectionArray;
@property(nonatomic,strong)NSMutableArray * townArray;
@property(nonatomic,strong)NSMutableArray * currentArray;
@property(nonatomic,strong)NSMutableArray * addressArray;
@property(nonatomic,strong)NSString * captionId;
@property(nonatomic,strong)NSString * cityId;
@property(nonatomic,strong)NSString * sectionId;

@property(nonatomic,assign)NSInteger level;
@property(nonatomic,assign)NSInteger selectedIndex;
@property(nonatomic,strong)NSString * headImageStr;
@property(nonatomic,strong)NSString * headImageUrl;
@property(nonatomic,strong)NSString * knowledgeId;

@property (weak, nonatomic) IBOutlet UIImageView *personLevel;//会员等级

@end

@implementation PersionInfoViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (![Common getLoginStatus]) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _captionArray = [NSMutableArray array];
    _sectionArray = [NSMutableArray array];
    _cityArray = [NSMutableArray array];
    _townArray = [NSMutableArray array];
    _currentArray = [NSMutableArray array];
    _addressArray = [NSMutableArray array];
    _level = 0;
    _selectedIndex = 0;
    _headImageUrl = @"";
    _headImageStr = @"";
    _knowledgeId = @"";
    DbDao *dao = [DbDao sharedInstance];
    NSArray *cityArr = [dao getCityArea:@"select * from sys_area where a_level = 3"];
    for (CityArea *area  in cityArr) {
        [_captionArray addObject:area.a_name];
    }
    _currentArray = _captionArray;
    [self initViewLayout];
    [self getPersonInfo];
}
#pragma mark  布局调整--=========================================
- (void)initViewLayout{
    
    //功能栏
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navgationView];
    [self adaptiveViewLayout:self.mainScrollview];
    [self adaptiveViewLayout:self.userIconView];
    [self adaptiveViewLayout:self.userNameView];
    [self adaptiveViewLayout:self.userLevelView];
    [self adaptiveViewLayout:self.userSexView];
    [self adaptiveViewLayout:self.userBirthdayView];
    [self adaptiveViewLayout:self.userAreaView];
    [self adaptiveViewLayout:self.knowledgeView];
    [self adaptiveViewLayout:self.changeAddressVIew];
    
    
    [_personNameField setValue:[UIColor colorWithWhite:0.463 alpha:1.000]
               forKeyPath:@"_placeholderLabel.textColor"];
    
    
    _boyButton = [[ScroButton alloc]initWithFrame:flexibleFrame(CGRectMake(250, 12, 48, 23), NO) title:@"女" selectedTitle:@"男" selectedColor:[UIColor colorWithRed:0.988 green:0.580 blue:0.055 alpha:1.000] cancelColor:[UIColor colorWithWhite:0.620 alpha:1.000] selected:NO  oval:(BOOL)NO complect:^(NSInteger index) {
    }];
    
    [self.userSexView addSubview:_boyButton];
    //广告栏
    self.mainScrollview.contentSize = CGSizeMake(1,self.mainScrollview.frame.size.height+1);
    
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [_addressArray addObject:_captionArray[0]];
    [self drowButton];
    
    
}
#pragma mark  返回--=========================================
- (IBAction)backClick:(UIButton *)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}


#pragma mark == 获取用户信息
- (void)getPersonInfo{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryPersonalData withHttpType:@"POST" withTag:SX_SX_queryPersonalData];
}

#pragma mark  用户信息编辑事件--=========================================
- (IBAction)userInfoEditClick:(UIButton *)sender {
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_headImageStr forKey:@"avatarId"];
    [dic setObject:_personNameField.text forKey:@"museNickName"];
    if (_boyButton.ifSelected) {
         [dic setObject:@"1" forKey:@"suseGenderId"];
    }else{
     [dic setObject:@"2" forKey:@"suseGenderId"];
    }
   
    [dic setObject:_brithdayLabel.text forKey:@"museBirthday"];
    [dic setObject:_homePlaceLabel.text forKey:@"suseContactAddr"];
    [dic setObject:_knowledgeId forKey:@"suseEducId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_updatePeronalData withHttpType:@"POST" withTag:SX_SX_updatePeronalData];
    
    
}
#pragma mark  设置生日--===
- (IBAction)setBrithday:(id)sender {
    
    NSDate * date  = [[NSDate alloc]init];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];//格式化
    [formatter setDateFormat:@"yyyy-MM-dd"];
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] ];
    NSString * string =[formatter stringFromDate:date];
    NSInteger Year = [[string substringToIndex:4]integerValue];
    NSInteger Month = [[string substringWithRange:NSMakeRange(5, 2)]integerValue];
    NSInteger  Day = [[string substringFromIndex:8]integerValue];
    if (_brithdayLabel.text.length>=10) {
        Year = [[_brithdayLabel.text substringToIndex:4]integerValue];
        Month = [[_brithdayLabel.text substringWithRange:NSMakeRange(5, 2)]integerValue];
        Day = [[_brithdayLabel.text substringFromIndex:8]integerValue];
    }
    
    
    ThreeLevelPickerView * pickerView = [[ThreeLevelPickerView alloc]initWithSelectedAtRows:@[@(Year-1),@(Month-1),@(Day-1)] complect:^(NSString *str) {
        _brithdayLabel.text = str;
    }];
    [pickerView show];
}

- (void)changeLevel:(UIButton *)sender{
    _level = sender.tag - 100;
    if (_level == 0) {
        _currentArray = _captionArray;
    }else if (_level == 1){
        _currentArray = _cityArray;
    }else if (_level == 2){
        _currentArray = _sectionArray;
    }else if(_level == 3){
        _currentArray = _townArray;
    }
    
    
    
    NSMutableArray * array = [NSMutableArray array];
    for (int i = 0; i<=_level; i++) {
        NSString * string = _addressArray[i];
        [array addObject:string];
    }
    _addressArray = array;
    [self drowButton];
    [_tableView reloadData];
}

- (void)drowButton{
    
    for (UIButton * button in _changeAddressVIew.subviews) {
        if (button.tag>=100) {
            [button removeFromSuperview];
        }
    }
    
    for (int i = 0; i<_addressArray.count; i++) {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = flexibleFrame(CGRectMake(i*80, 47, 80, 38), YES);
        [button setTitle:_addressArray[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithWhite:0.271 alpha:1.000] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor clearColor];
        button.titleLabel.font = [UIFont systemFontOfSize:16*VerticalTexeRatio()];
        [button addTarget:self action:@selector(changeLevel:) forControlEvents:UIControlEventTouchUpInside];
        
        button.tag = 100+i;
        if (i==_addressArray.count-1) {
            [button setTitleColor:[UIColor colorWithRed:1.000 green:0.659 blue:0.035 alpha:1.000] forState:UIControlStateNormal];
            UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(10, 36, 60, 2), YES)];
            line.backgroundColor = [UIColor colorWithRed:0.992 green:0.655 blue:0.000 alpha:1.000];
            [button addSubview:line];
        }
        [_changeAddressVIew addSubview:button];
    }
}



- (IBAction)hideMenuView:(id)sender {
    [UIView animateWithDuration:0.1 animations:^{
        _changeAddressVIew.alpha=0;
        _maskView.alpha = 0;
    }completion:^(BOOL finished) {
        _changeAddressVIew.hidden = YES;
        _maskView.hidden = YES;
    }];
    
}
#pragma mark  设置居住地--===
- (IBAction)setHomePlace:(id)sender {
    _changeAddressVIew.hidden = NO;
    _maskView.hidden = NO;
    [UIView animateWithDuration:0.1 animations:^{
        _changeAddressVIew.alpha=1;
        _maskView.alpha = 1;
    }];
}

#pragma mark  设置学历--===
- (IBAction)setKnowledge:(id)sender {
    NSArray * array = @[@"小学",@"初中",@"高中",@"中专",@"大专",@"本科",@"研究生",@"博士生"];
    NSInteger index = 0;
    for (NSInteger i = 0; i<array.count; i++) {
        NSString * str = array[i];
        if ([_knowledgeLabel.text isEqualToString:str]) {
            index = i;
        }
    }
    
    OneLevelPickerView * pickerView = [[OneLevelPickerView alloc]initWithTitles:array selectedAtRow:(NSInteger)index complect:^(NSString *str) {
        _knowledgeLabel.text = str;
        for (NSInteger i = 0; i<array.count; i++) {
            NSString * str = array[i];
            if ([_knowledgeLabel.text isEqualToString:str]) {
                _knowledgeId = [NSString stringWithFormat:@"%ld",i+1];
            }
        }
    }];
    [pickerView show];
    
}

#pragma mark - 上传图片--------------------------
- (void) imageUpload:(int)numberImg:(UIImage *)imageImage{
    NSString *url = [NSString stringWithFormat:@"http://%@%@",IP_Address_Fresh,SX_uploadCommentImg];
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    CGSize newSize = CGSizeMake(80, 80);
    UIGraphicsBeginImageContext(newSize);
    [imageImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData* data  = UIImageJPEGRepresentation(newImage, 0.7);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //设置HTTPHeader中Content-Type的值
    NSString* content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
//    [body appendFormat:@"Content-Type: %@\r\n\r\n",content];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x-- 
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *headerUserAgent=@"";
    if ([Common getLoginStatus]) {
        NSString *userName = [[Common getLoginInfo] objectForKey:Key_User_nickname];
        NSString *userId  = [NSString stringWithFormat:@"%@",[[Common getLoginInfo] objectForKey:Key_User_userId]];
        NSString *encryptPwd  = [Common shaEncrypt:[[Common getLoginInfo] objectForKey:Key_User_password]];
        NSString *localUserIdentify  = [[UIDevice currentDevice].identifierForVendor UUIDString];
        headerUserAgent = [NSString stringWithFormat:@"%@|%@|%@|%@",userName,userId,encryptPwd,localUserIdentify];
    }else{
        headerUserAgent = @"|||";
    }
    
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置User-Agent
    [request setValue:headerUserAgent forHTTPHeaderField:@"User-Agent"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    //上传文件开始
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //获得返回值
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
    
    //取得返回的图片名
//    NSArray* array = [returnString componentsSeparatedByString:@"###"];
    NSString * image = [NSString stringWithFormat:@"%@", dictionary[@"result"][0][@"simaId"]];
    if (image.length>0) {
        _headImageStr = image;
        _headImageUrl = dictionary[@"result"][0][@"simaImagUri"];
    }else{
    _headImageStr = @"";
    }
}



#pragma mark  用户头像编辑事件--=========================================
- (IBAction)userIconEditClick:(id)sender {
    PhotoPopView * photoPopView = [[PhotoPopView alloc]initWithcomplect:^(NSInteger index) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.userIconImage.image = image;
                    self.userIconImage.layer.masksToBounds = YES;
                    self.userIconImage.layer.cornerRadius = 25*VerticalRatio();
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.userIconImage.image = image;
                    self.userIconImage.layer.masksToBounds = YES;
                    self.userIconImage.layer.cornerRadius = 25*VerticalRatio();
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
            
            
            
        }else {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.userIconImage.image = image;
                    self.userIconImage.layer.masksToBounds = YES;
                    self.userIconImage.layer.cornerRadius = 25*VerticalRatio();
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    self.userIconImage.image = image;
                    self.userIconImage.layer.masksToBounds = YES;
                    self.userIconImage.layer.cornerRadius = 25*VerticalRatio();
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeCircular;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
        }
        
    }];
    [photoPopView show];
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentify = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify ];
    if (cell==nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIButton class] ]||[view isKindOfClass:[UIView class]]) {
            [view removeFromSuperview];
        }
    }
    
    UILabel * label = [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 92, 40), YES)];
    label.font = [UIFont systemFontOfSize:16*VerticalTexeRatio()];
    label.textColor = [UIColor colorWithWhite:0.271 alpha:1.000];
    label.textAlignment = NSTextAlignmentCenter;
    label.text = _currentArray[indexPath.row];
    for (int i = 0; i<_addressArray.count; i++) {
        if ([label.text isEqualToString:_addressArray[i]]) {
            label.frame = flexibleFrame(CGRectMake(0, 0, 81, 40), YES);
            label.textColor = [UIColor colorWithRed:1.000 green:0.647 blue:0.035 alpha:1.000];
            UIImageView * image = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(81, 16, 11, 8), YES)];
            image.image = [UIImage imageNamed:@"changeAddress2"];
            [cell addSubview:image];
        }
    }
    [cell addSubview:label];
    
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _currentArray.count;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 40*VerticalRatio();
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_level == 0) {
        if (_captionArray.count!=0) {
            if (_addressArray.count>=1) {
                [_addressArray replaceObjectAtIndex:0 withObject:_captionArray[indexPath.row]];
            }else{
                [_addressArray addObject:_captionArray[indexPath.row]];
            }
        }
        
    }else if (_level==1){
        if (_cityArray.count!=0) {
            if (_addressArray.count>=2) {
                [_addressArray replaceObjectAtIndex:1 withObject:_cityArray[indexPath.row]];
            }else{
                [_addressArray addObject:_cityArray[indexPath.row]];
            }        }
        
    }else if (_level == 2||(_level == 3&&_townArray.count==0)){
        if (_sectionArray.count!=0) {
            if (_addressArray.count>=3) {
                [_addressArray replaceObjectAtIndex:2 withObject:_sectionArray[indexPath.row]];
            }else{
                [_addressArray addObject:_sectionArray[indexPath.row]];
            }        }
        
    }else if (_level == 3){
        if (_townArray.count!=0) {
            if (_addressArray.count>=4) {
                [_addressArray replaceObjectAtIndex:3 withObject:_townArray[indexPath.row]];
            }else{
                [_addressArray addObject:_townArray[indexPath.row]];
            }        }
       
    }
    
    [self drowButton];
    
    
    if (_level < 3) {
        _level++;
    }
    
    
    if (_level == 1) {
        DbDao *dao = [DbDao sharedInstance];
        NSArray *cityArr = [dao getCityArea:[NSString stringWithFormat:@"select * from sys_area where a_name = '%@'",_captionArray[indexPath.row] ]];
        CityArea *area = cityArr[0];
        NSArray *areaArr = [dao getCityArea:[NSString stringWithFormat:@"select * from sys_area where a_parent_id = %ld",area.a_id]];
        _captionId = [NSString stringWithFormat:@"%ld",area.a_id];
        [_cityArray removeAllObjects];
        for (CityArea *area  in areaArr) {
            [_cityArray addObject:area.a_name];
        }
        if (_cityArray.count!=0) {
            _currentArray = _cityArray;
        }
    }else if (_level==2 ){
        DbDao *dao = [DbDao sharedInstance];
        NSArray *cityArr = [dao getCityArea:[NSString stringWithFormat:@"select * from sys_area where a_name = '%@'",_cityArray[indexPath.row]]];
        CityArea *area = cityArr[0];
        NSArray *areaArr = [dao getCityArea:[NSString stringWithFormat:@"select * from sys_area where a_parent_id = %ld",area.a_id]];
        _cityId = [NSString stringWithFormat:@"%ld",area.a_id];
        [_sectionArray removeAllObjects];
        for (CityArea *area  in areaArr) {
            [_sectionArray addObject:area.a_name];
        }
        
        if (_sectionArray.count!=0) {
            _currentArray = _sectionArray;
        }
        
    }else if(_level == 3 ){
        DbDao *dao = [DbDao sharedInstance];
        NSArray *cityArr = [dao getCityArea:[NSString stringWithFormat:@"select * from sys_area where a_name = '%@'",_sectionArray[indexPath.row]]];
        CityArea *area = cityArr[0];
        NSArray *areaArr = [dao getCityArea:[NSString stringWithFormat:@"select * from sys_area where a_parent_id = %ld",area.a_id]];
        _cityId = [NSString stringWithFormat:@"%ld",area.a_id];
        [_townArray removeAllObjects];
        for (CityArea *area  in areaArr) {
            [_townArray addObject:area.a_name];
        }
        if (_townArray.count!=0) {
            _currentArray = _townArray;
        }
        
    }
    _selectedIndex = indexPath.row;
    [_tableView reloadData];
    
    if (_level==3 ) {
        [UIView animateWithDuration:0.1 animations:^{
            _changeAddressVIew.alpha = 0;
            _maskView.alpha = 0;
        }completion:^(BOOL finished) {
            _maskView.hidden = YES;
            _changeAddressVIew.hidden = YES;
        }];
        NSString * address = @"";
        if (_addressArray.count==3) {
            address = [NSString stringWithFormat:@"%@%@%@",_addressArray[0],_addressArray[1],_addressArray[2]];
        }else{
            address = [NSString stringWithFormat:@"%@%@%@%@",_addressArray[0],_addressArray[1],_addressArray[2],_addressArray[3]];
        }

        _homePlaceLabel.text = address;


    }
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if (tag==SX_SX_queryPersonalData) {
        
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSDictionary * dic = database[@"result"][0];
            
            if ([dic[@"sgenName"]isEqualToString:@"男性"]) {
                _boyButton.ifSelected = YES;
            }else{
                _boyButton.ifSelected = NO;
            }
            
            _personNameField.text = [NSString stringWithFormat:@"%@",dic[@"museNickName"]];
            _knowledgeLabel.text = [NSString stringWithFormat:@"%@",dic[@"education"]];
            NSArray * array = @[@"小学",@"初中",@"高中",@"中专",@"大专",@"本科",@"研究生",@"博士生"];
            for (NSInteger i = 0; i<array.count; i++) {
                NSString * str = array[i];
                if ([_knowledgeLabel.text isEqualToString:str]) {
                    _knowledgeId = [NSString stringWithFormat:@"%ld",i+1];
                }
            }
            _headImageStr = [NSString stringWithFormat:@"%@",dic[@"resImagePath"]];
            if (_headImageStr.length>0) {
                [_userIconImage sd_setImageWithURL:[NSURL URLWithString:_headImageStr]];
            }
            
            
            NSString * vipLevel = [NSString stringWithFormat:@"%@",dic[@"memberVipImg"]];
            if (vipLevel.length>0) {
                [_personLevel sd_setImageWithURL:[NSURL URLWithString:vipLevel]];
            }
            
            _userIconImage.layer.masksToBounds = YES;
            _userIconImage.layer.cornerRadius = 25*VerticalRatio();
            _headImageStr = [NSString stringWithFormat:@"%@",dic[@"resImageId"]];
            
            _homePlaceLabel.text = [NSString stringWithFormat:@"%@",dic[@"suseContactAddr"]];
            if ([NSString stringWithFormat:@"%@",dic[@"museBirthday"] ].length>0) {
                NSInteger num = [dic[@"museBirthday"] integerValue]/1000;//（重点）
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];//格式化
                [formatter setDateFormat:@"yyyy-MM-dd"];
//                [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] ];
                NSDate *date =  [NSDate dateWithTimeIntervalSince1970:num];
                NSString *confromTimespStr = [formatter stringFromDate:date];
                _brithdayLabel.text = confromTimespStr;
            }
        }
    }else if (tag == SX_SX_updatePeronalData){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
         
            if (_headImageUrl.length>0) {
                //更新用户头像
                NSMutableDictionary *dataUser = (NSMutableDictionary *)[Common getLoginInfo];
                [dataUser setObject:_headImageUrl forKey:Key_User_head];
                //写入文件
                NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                NSString *path=[paths    objectAtIndex:0];
                NSString *filename=[path stringByAppendingPathComponent:@"myUserInfo.plist"];
                [dataUser writeToFile:filename atomically:YES];
                
            }
            [self.navigationController popViewControllerAnimated:YES];
                 [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  ];
           
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
            
            //
            [self dismissWaitDialog];
            
            
        }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




@end
